package com.surelution.projects.crm


import java.text.NumberFormat;
import java.util.Date;


import com.surelution.projects.crm.core.TimeUtils;
/**
 * 
 * @author Miracle
 *客户信息编码：
 *客户编码
 *客户名称
 *主卡卡号
 *地址
 *联系人
 *联系电话
 *首次消费时间
 *价格优惠额度
 *年度累计销量
 *信息录入单位——录入客户的加油站名称
 *购油次数
 *开户时间
 */
class Market {

    static constraints = {
		marketName(unique:['name','station'])
		discountNum nullable:true
		discountNum blank:true
		gasPredictSale nullable:true
		gasPredictSale blank:true
		fuelPredictSale nullable:true
		fuelPredictSale blank:true
		isLocked nullable:true
		firstSaleTime nullable:true
		marketCardNo nullable:true
		marketCardNo blank:true
		longitude nullable:true
		longitude blank:true
		latitude nullable:true
		latitude blank:true
		betweenDistance nullable:true
		betweenDistance blank:true
		requirement nullable:true
		requirement blank:true
		carePoint nullable:true
		carePoint blank:true
		provideSite nullable:true
		provideSite blank:true
		name nullable:false
		name blank:false
		preMarketType nullable:true
    }
	
	static hasMany = [pictures:MarketPicture]
	static transients = ['annualSaleNumber','cardMarketTime','cardType','annualDieselAmount',
		'annualGasAmount','effectiveMonthOfThisYear','marketGasSales','contractAmount']
	/**
	 * 客户编码
	 */
	String marketName
	String name
	String marketCardNo
	String address
	String manager
	String managerTel
	Date firstSaleTime
	Date startTime
	String discountNum
	MarketSpecies marketType
	MarketSpecies preMarketType
	/**
	* 供油单位
	*/
    String provideSite
	/**
	 * 客户到加油站的距离（公里）
	 */
	String betweenDistance
	/**
	 * 客户诉求
	 */
	String requirement
	/**
	 * 客户关注点
	 */
	String carePoint
	/**
	 * 汽油销量预估（升/月）
	 */
	Float gasPredictSale
	/**
	* 柴油油销量预估（升/月）
	*/
   Float fuelPredictSale
	
	OwnStation station
	StationArea area
	String longitude
	String latitude
	Date createTime
	/**
	 * 协议购油量,既柴汽油预估量总和
	 */
	Float getContractAmount() {
		gasPredictSale + fuelPredictSale
    }
	
	List<MarketGasSale> marketGasSales
	
	MarketType type
	Boolean detailedInfoValiable
	Boolean isLocked
	
	List<MarketPicture> pictures
	Float getAnnualSaleNumber() {
//		Calendar c = Calendar.getInstance()
//		int year = c.get(Calendar.YEAR)
//		c.clear()
//		Date now = new Date()
//		c.set(year, 0, 1)
//		def firstSight = c.getTime()
//		def l = CardConsume.createCriteria().get{
//			createAlias("member", "m")
//			projections {
//				sum("amount")
//			}
//			eq("m.market.id", id)
//			ge("tradeTime", firstSight)
//			le("tradeTime", now)
//		}
//		l?l/1000:0
		annualGasAmount + annualDieselAmount

	}
	
	/**
	 * 年度汽油销量
	 * @return
	 */
	Float getAnnualGasAmount() {
		Calendar c = Calendar.getInstance()
		int year = c.get(Calendar.YEAR)
		c.clear()
		c.set(year, 0, 1)
		def firstSight = c.getTime()
		def sale = MarketGasSale.createCriteria().get {
			projections {
				sum("saleNumber")
			}
			eq("market.id", id)
			eq("sumType", MarketGasSale.SUM_TYPE_MONTH)
			ge("saleGasTime", firstSight)
		}
		sale?sale:0
	}
	
	/**
	 * 年度柴油销量
	 * @return
	 */
	Float getAnnualDieselAmount() {
		def firstSight = TimeUtils.getFirstSightOfThisYear()
		def sale = MarketGasSale.createCriteria().get {
			projections {
				sum("dieselOilNumber")
			}
			eq("market.id", id)
			eq("sumType", MarketGasSale.SUM_TYPE_MONTH)
			ge("saleGasTime", firstSight)
		}
		sale?sale:0
	}
	
	/**
	 * 该客户开卡至今，本年度共有多少个有效月份，比如，该客户在去年开卡，那么，其开卡月份就是当前的月份数
	 * 如果该客户在今年开卡，那么，月份数就是开卡月份到当前月份的差值
	 * 这样么做有一个问题，就是，无法取得开卡月份到特定日期的月份数目
	 * @return
	 */
	Integer getEffectiveMonthOfThisYear() {
		def date = getCardMarketTime()
		if(date < TimeUtils.getFirstSightOfThisYear()) {
			date = TimeUtils.getFirstSightOfThisYear()
		}
		Calendar c = Calendar.instance
		int month = c.get(Calendar.MONTH)
		c.setTime(date)
		def m = month - c.get(Calendar.MONTH)
		m==0?1:m //如果月数等于0，比如每年的一月，作为1个月
	}
	
	/**
	* 获取首次转变为持卡客户的时间
	* @return
	*/
   Date getCardMarketTime() {
//	   def day = MemberCard.createCriteria().get{
//		   projections {
//			   min("connectTime")
//		   }
//		   eq("market.id", id)
//	   }
	   def day = CardConsume.createCriteria().get{
		  createAlias("member", "m")
		  projections {
			  min("tradeTime")
		  }
		  eq("m.market.id", id)
	  }
	   day?day:null
   }
   
   public List<MarketGasSale> getMarketGasSales() {
	   MarketGasSale.createCriteria().list {
		   eq('market.id', id)
		   eq('sumType', MarketGasSale.SUM_TYPE_MONTH)
		   order("saleGasTime", "desc")
	   }
   }
	   
	
	/**
	 * 获取持卡客户类别：A管理级别、B公司级别、C站级别（10+吨,5-10吨,,0-5吨）
	 * @return
	 */
	String getCardType() {
		def average = (getAnnualDieselAmount() + getAnnualGasAmount())/getEffectiveMonthOfThisYear()
		if(average > 10) {
			return "A"
		}
		if(average > 5) {
			return "B"
		}
		return "C"
	}
	
	def beforeInsert = {
		if(discountNum == null || annualSaleNumber == null) {
			detailedInfoValiable = false
		} else {
			detailedInfoValiable = true
		}
	}
	
	def beforeUpdate = {
		if(discountNum == null || annualSaleNumber == null) {
			detailedInfoValiable = false
		} else {
			detailedInfoValiable = true
		}
	}
}
